package com.xinghou.platform.dao.main.aspect;

import org.aspectj.lang.ProceedingJoinPoint;

import com.xinghou.platform.dao.main.common.DBUserRelationLevelCached;
import com.xinghou.platform.model.main.UserRelationTo;
import com.xinghou.platform.util.JsonUtil;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserRelationToCacheAspect extends DBUserRelationLevelCached {
	@Pointcut("execution(public * com.xinghou.platform.dao.main.UserRelationToDAO.getUserRelationToById(..))")
	public void getUserRelationToByUserId(){
	}

	@Pointcut("execution(public * com.xinghou.platform.dao.main.UserRelationToDAO.updateUserRelationTo(..))")
	public void updateUserRelationTo(){
	}

	@Around("getUserRelationToByUserId()")
	public UserRelationTo getUserRelationToByUserId(ProceedingJoinPoint pjp) throws Throwable{
		String fromUserId = ((Object[])pjp.getArgs())[1].toString();
		String toUserId = ((Object[])pjp.getArgs())[0].toString();
		String key = String.format(CACHE_URTO_INFOID,fromUserId,toUserId);
		Object jsonToken = getRedisClient().get(key, CACHED_DB_INDEX);
		if(jsonToken == null){
			UserRelationTo userRelationTo = (UserRelationTo)pjp.proceed();
			if(userRelationTo != null)
				getRedisClient().set(key, JsonUtil.toJson(userRelationTo), CACHED_DB_INDEX);
			return userRelationTo;
		}else{
			UserRelationTo userRelationTo = (UserRelationTo)JsonUtil.fromJson(jsonToken.toString(), UserRelationTo.class);
			return userRelationTo;
		}
	}

	@Around("updateUserRelationTo()")
	public int updateUserRelationTo(ProceedingJoinPoint pjp) throws Throwable{
		UserRelationTo userRelationTo = (UserRelationTo)((Object[])pjp.getArgs())[0];
		int returnno = (int) pjp.proceed();
		String keyInfoId = String.format(CACHE_URTO_INFOID , userRelationTo.getFromuserid(),userRelationTo.getTouserid());
		if(getRedisClient().exists(keyInfoId, CACHED_DB_INDEX)){
			getRedisClient().set(keyInfoId, JsonUtil.toJson(userRelationTo), CACHED_DB_INDEX);
		}
		
		return returnno;
	}
	
}
